import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from '../utils/axios'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  const permissions = ref(JSON.parse(localStorage.getItem('permissions') || '[]'))
  const menus = ref(JSON.parse(localStorage.getItem('menus') || '[]'))
  const isLoggedIn = computed(() => !!token.value)

  // 登录
  const login = async (username, password) => {
    try {
      const response = await axios.post('/auth/login', {
        username,
        password
      })
      
      if (response.data.code === 200) {
        const { accessToken, userInfo: userData } = response.data.data
        
        // 保存到store
        token.value = accessToken
        userInfo.value = {
          ...userData,
          role: userData.roles?.[0] || userData.role || 'USER', // 优先使用roles数组的第一个，兼容role字段
          roles: userData.roles || [userData.role || 'USER'] // 确保roles字段存在
        }
        
        console.log('登录成功，用户信息:', userInfo.value)
        
        // 保存到localStorage
        localStorage.setItem('token', accessToken)
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        
        // 设置axios默认token
        axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`
        
        return true
      } else {
        throw new Error(response.data.message || '登录失败')
      }
    } catch (error) {
      console.error('Login error:', error)
      if (error.response?.data?.message) {
        throw new Error(error.response.data.message)
      } else if (error.message) {
        throw new Error(error.message)
      } else {
        throw new Error('登录失败，请检查网络连接')
      }
    }
  }

  // 登出
  const logout = async () => {
    try {
      // 调用后端登出API
      if (token.value) {
        await axios.post('/auth/logout', {}, {
          headers: { Authorization: `Bearer ${token.value}` }
        })
      }
    } catch (error) {
      console.error('Logout API error:', error)
      // 即使API调用失败，也要清除本地状态
    } finally {
      // 清除store
      token.value = ''
      userInfo.value = {}
      
      // 清除localStorage
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      
      // 清除axios默认token
      delete axios.defaults.headers.common['Authorization']
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      if (!token.value) return null
      
      const response = await axios.get('/auth/info', {
        headers: { Authorization: `Bearer ${token.value}` }
      })
      
      if (response.data.code === 200) {
        const userData = response.data.data
        userInfo.value = {
          ...userData,
          role: userData.roles?.[0] || userData.role || 'USER',
          roles: userData.roles || [userData.role || 'USER']
        }
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        console.log('获取用户信息成功:', userInfo.value)
        return userInfo.value
      } else {
        throw new Error(response.data.message || '获取用户信息失败')
      }
    } catch (error) {
      console.error('Get user info error:', error)
      // 如果获取用户信息失败，可能是token过期，清除本地状态
      if (error.response?.status === 401) {
        logout()
      }
      return null
    }
  }

  // 更新用户信息
  const updateUserInfo = (newUserInfo) => {
    userInfo.value = { ...userInfo.value, ...newUserInfo }
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }

  // 刷新token
  const refreshToken = async () => {
    try {
      if (!token.value) return false
      
      const response = await axios.post('/auth/refresh', {}, {
        headers: { Authorization: `Bearer ${token.value}` }
      })
      
      if (response.data.code === 200) {
        const newToken = response.data.data
        token.value = newToken
        localStorage.setItem('token', newToken)
        axios.defaults.headers.common['Authorization'] = `Bearer ${newToken}`
        return true
      } else {
        throw new Error(response.data.message || '刷新token失败')
      }
    } catch (error) {
      console.error('Refresh token error:', error)
      // 刷新失败，清除本地状态
      logout()
      return false
    }
  }

  // 检查权限
  const hasPermission = (permission) => {
    if (!isLoggedIn.value) return false
    
    // 管理员拥有所有权限
    if (userInfo.value.role === 'ADMIN' || userInfo.value.role === 'SUPER_ADMIN') return true
    
    // 检查具体权限
    return permissions.value.includes(permission)
  }

  // 检查角色
  const hasRole = (role) => {
    if (!isLoggedIn.value) return false
    
    // 检查单个角色字段
    if (userInfo.value.role === role) return true
    
    // 检查角色数组
    if (userInfo.value.roles && Array.isArray(userInfo.value.roles)) {
      return userInfo.value.roles.includes(role)
    }
    
    return false
  }

  // 获取用户权限
  const getUserPermissions = async () => {
    try {
      if (!token.value) return []
      
      const response = await axios.get('/permissions/user')
      if (response.data.code === 200) {
        const permissionList = response.data.data
        permissions.value = permissionList.map(p => p.permissionCode)
        localStorage.setItem('permissions', JSON.stringify(permissions.value))
        return permissions.value
      }
    } catch (error) {
      console.error('Get user permissions error:', error)
    }
    return []
  }

  // 获取用户菜单
  const getUserMenus = async () => {
    try {
      if (!token.value) return []
      
      const response = await axios.get('/menus/user')
      if (response.data.code === 200) {
        menus.value = response.data.data
        localStorage.setItem('menus', JSON.stringify(menus.value))
        return menus.value
      }
    } catch (error) {
      console.error('Get user menus error:', error)
    }
    return []
  }

  return {
    // 状态
    token,
    userInfo,
    permissions,
    menus,
    isLoggedIn,
    
    // 方法
    login,
    logout,
    getUserInfo,
    updateUserInfo,
    refreshToken,
    hasPermission,
    hasRole,
    getUserPermissions,
    getUserMenus
  }
})
